package com.kingyun.gpsinspection.purificationservice.services.som.innerservice.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cqhilink.api.common.utils.HttpClientUtil;
import com.cqhilink.api.common.utils.UniqueUtil;
import com.cqhilink.api.common.utils.date.DateStyle;
import com.cqhilink.api.common.utils.date.DateUtil;
import com.cqhilink.api.common.utils.enums.RespCodeEnum;
import com.kingyun.gpsinspection.purificationservice.common.constant.BackMessage;
import com.kingyun.gpsinspection.purificationservice.common.utils.ETUtils;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.som.ElectronTemplateItemMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.som.ElectronTemplateMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.som.ElectronTemplateValueMapper;
import com.kingyun.gpsinspection.purificationservice.facade.model.som.ElectronTemplate;
import com.kingyun.gpsinspection.purificationservice.facade.model.som.ElectronTemplateItem;
import com.kingyun.gpsinspection.purificationservice.facade.model.som.ElectronTemplateValue;
import com.kingyun.gpsinspection.purificationservice.facade.model.webservicesmodel.EntityValue;
import com.kingyun.gpsinspection.purificationservice.facade.service.som.SomElectronTemplateValueService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.*;

/**
 * @Author 卢曼成
 * @Description 电子模版值实现类
 * @CreateDateTime 2017-06-05 17:10
 **/
public class SomElectronTemplateValueServiceImpl implements SomElectronTemplateValueService {
    private static Logger logger = LoggerFactory.getLogger(InOutServiceImpl.class);
    @Autowired
    private ElectronTemplateValueMapper electronTemplateValueMapper;
    @Autowired
    private ElectronTemplateMapper electronTemplateMapper;
    @Autowired
    private ElectronTemplateItemMapper electronTemplateItemMapper;
    @Value("#{configProperties['opc_url']}")
    private String configUril;

    /**
     * 分页查询
     *
     * @param param
     * @return
     */
    @Override
    public Map<String, Object> findPageList(ElectronTemplateValue param) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("rows", null);
        map.put("total", null);
        return map;
    }

    /**
     * 根据ID查询
     *
     * @param etvId
     * @return
     */
    @Override
    public Map<String, Object> getByParam(String etvId) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        return map;
    }

    /**
     * 保存
     *
     * @param str
     * @param userId
     * @return
     */
    @Override
    public Map<String, Object> save(String str, String userId) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        List<ElectronTemplateValue> list = JSONArray.parseArray(str, ElectronTemplateValue.class);
        if (list == null || list.size() == 0) {
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", "数据异常!");
            return map;
        }
        ElectronTemplateValue etv = new ElectronTemplateValue();
        etv.setEtId(list.get(0).getEtId());
        Date date = new Date();
        etv.setCreateTime(date);
        Integer number = electronTemplateValueMapper.selectByNumber(etv);//错误 日期问题
        if (number == null || number == 0) {
            number = 1;
        } else {
            number++;
        }

        for (ElectronTemplateValue e : list) {
            e.setEtValueId(UniqueUtil.uuid());
            e.setStartTime(date);
            e.setEtvNumber(number);
            e.setEndTime(date);
            e.setCreatorId(userId);
            e.setCreateTime(date);
            e.setModifyerId(userId);
            e.setModifyTime(date);
        }
        try {
            int num = electronTemplateValueMapper.insertList(list);
            map.put("state", num > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", num > 0 ? BackMessage.ADD_OK : BackMessage.ADD_FAIL);
        } catch (Exception e) {
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", BackMessage.ADD_FAIL);
        }
        return map;
    }

    /**
     * 修改
     *
     * @param param
     * @return
     */
    @Override
    public Map<String, Object> update(ElectronTemplateValue param) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        return map;
    }

    /**
     * 逻辑删除
     *
     * @param param
     * @return
     */
    @Override
    public Map<String, Object> deleteKey(ElectronTemplateValue param) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        return map;
    }

    /**
     * 查询当前日期当前小时是否执行巡检
     *
     * @param etId
     * @return
     */
    @Override
    public Map<String, Object> isExecute(String etId) {
        Map<String, Object> map = new HashMap<String, Object>();
        if (StringUtils.isEmpty(etId)) {
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", "数据异常!");
            return map;
        }
        ElectronTemplateValue etv = new ElectronTemplateValue();
        etv.setEtId(etId);
        etv.setEtvValue(DateUtil.DateToString(new Date(), "yyyy-MM-dd HH"));
        try {
            int num = electronTemplateValueMapper.selectByParamCount(etv);
            map.put("state", num > 0 ? RespCodeEnum.RESP_CODE_ENUM_false.code() : RespCodeEnum.RESP_CODE_ENUM_true.code());
            map.put("msg", num > 0 ? "该时间段已经巡检完成,无需重复巡检!" : BackMessage.OPERATE_OK);
        } catch (Exception e) {
            logger.error("ElectronTemplate 巡检验证出错" + e.getMessage());
            e.printStackTrace();
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", e.getMessage());
        }
        return map;
    }

    public static void main(String[] args) {
        try {

            System.out.println();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 组装数据
     *
     * @param etId
     * @return
     */
    @Override
    public String dataAssembling(String etId, boolean is, Date date) throws Exception {
        Map<String, Object> strMap = new HashMap<String, Object>();
        String startDate = null;
        String startDateTime = null;
        String endDateTime = null;
        if (date == null) {
            date = new Date();
            startDate = DateUtil.DateToString(date, DateStyle.YYYY_MM_DD);
            startDateTime = startDate + " 08:00:00";
            endDateTime = ETUtils.getAfterDate(date) + " 07:59:59";
            Date date2 = DateUtil.StringToDate(startDateTime, DateStyle.YYYY_MM_DD_HH_MM_SS);
            if (date2.getTime() > date.getTime()) {
                startDateTime = ETUtils.getFrontDate(date, -1) + " 08:00:00";
            }
        } else {
            startDate = DateUtil.DateToString(date, DateStyle.YYYY_MM_DD);
            startDateTime = startDate + " 08:00:00";
            endDateTime = ETUtils.getAfterDate(date) + " 07:59:59";
        }
        strMap.put("editable", is);//可以编辑
        strMap.put("reportType", "dateTime");//报表类型
        strMap.put("date", startDate);//报表类型
        ElectronTemplate et = electronTemplateMapper.selectByPrimaryKey(etId);
        if (et == null) {
            return null;
        }
        ElectronTemplateItem eti = new ElectronTemplateItem();
        eti.setEtId(etId);
        List<ElectronTemplateItem> etiList = electronTemplateItemMapper.selectByParamList(eti);
        ElectronTemplateValue etv = new ElectronTemplateValue();
        etv.setStartDateTime(startDateTime);
        etv.setEndDateTime(endDateTime);
        etv.setEtId(etId);
        List<ElectronTemplateValue> etvList = electronTemplateValueMapper.selectByValueList(etv);
        List<ElectronTemplateValue> itemList = electronTemplateValueMapper.selectByNumberList(etv);
        List<Map<String, Object>> list = null;
        //标题开始
        Map<String, Object> map = null;
        list = new ArrayList<Map<String, Object>>();
        map = new HashMap<String, Object>();
        map.put("fieldId", "dateTime");
        map.put("fieldName", "时间段");
        list.add(map);
        if (etiList != null && etiList.size() > 0) {
            opcValue(etiList, list, is);
        }
        map = new HashMap<String, Object>();
        map.put("fieldId", "description");
        map.put("fieldName", "备注");
        list.add(map);
        strMap.put("headField", list);
        if (!is) {//查看页面多显示信息
            strMap.put("reportName", et.getEtName() + "-" + et.getOrgName() + " 巡检明细查看");//标题
            map = new HashMap<String, Object>();
            map.put("fieldId", "createTime");
            map.put("fieldName", "实际巡检时间");
            list.add(map);
            map = new HashMap<String, Object>();
            map.put("fieldId", "createName");
            map.put("fieldName", "巡检人");
            list.add(map);
        } else {
            strMap.put("reportName", et.getEtName() + "-" + et.getOrgName() + " 巡检编辑");//标题
        }
        //标题结束

        //值开始
        list = new ArrayList<Map<String, Object>>();
        String thisTime = DateUtil.DateToString(date, "HH");
        if (is) {//处理编辑页面
            for (int i = 8; i < 32; i++) {
                int num = i + 1;
                map = new HashMap<String, Object>();
                String endTime = null;
                String startTime = i + "";
                startTime = startTime(startTime, i, num);
                endTime = endTime(endTime, i, num);
                map.put("dateTime", startTime + "点 - " + endTime + "点");
                dataValue1(itemList, etvList, etiList, map, startTime, thisTime);
                list.add(map);
            }
        } else {//处理查看页面
            for (int i = 8; i < 32; i++) {
                int num = i + 1;
                map = new HashMap<String, Object>();
                String endTime = null;
                String startTime = i + "";
                startTime = startTime(startTime, i, num);
                endTime = endTime(endTime, i, num);
                map.put("dateTime", startTime + "点 - " + endTime + "点");
                dataValue3(itemList, etvList, map, startTime, etiList.size());
                list.add(map);
            }
        }

        strMap.put("bodyData", list);//对应每行值
        //值结束
        return JSONObject.toJSONString(strMap);
    }

    //组装开始日期时间
    private String startTime(String startTime, int i, int num) {
        if (i < 10) {
            startTime = "0" + i;
        } else if (i >= 24) {
            int num2 = (i - 24);
            startTime = num2 < 10 ? "0" + num2 : num2 + "";
        }
        return startTime;
    }

    //组装结束日期时间
    private String endTime(String endTime, int i, int num) {
        if (i >= 23) {
            int num2 = (i - 24 + 1);
            endTime = num2 < 10 ? "0" + num2 : num2 + "";
        } else {
            endTime = num < 10 ? "0" + num : num + "";
        }
        return endTime;
    }


    /**
     * 处理编辑页面数据
     *
     * @param itemList
     * @param etvList
     * @param etiList
     * @param map
     * @param time
     * @param thisTime
     */
    private void dataValue1(List<ElectronTemplateValue> itemList, List<ElectronTemplateValue> etvList, List<ElectronTemplateItem> etiList, Map<String, Object> map, String time, String thisTime) {
        if (thisTime.equals(time)) {
            map.put("description", "");
            if (etiList != null && etiList.size() > 0) {
                if (etiList != null && etiList.size() > 0) {
                    for (ElectronTemplateItem e : etiList) {
                        map.put(e.getEtiId(), e.getOpcValue() != null ? e.getOpcValue() : "");
                    }
                    map.put("editable", true);
                }
            }
        } else {
            if (itemList != null && itemList.size() > 0) {
                Iterator<ElectronTemplateValue> it = itemList.iterator();
                while (it.hasNext()) {
                    ElectronTemplateValue e = it.next();
                    String startTime = DateUtil.DateToString(e.getStartTime(), "HH");
                    if (time.equals(startTime)) {
                        dataValue2(etvList, map, e.getEtvNumber(), etiList.size());
                        map.put("description", e.getDescription() != null ? e.getDescription() : "");
                        it.remove();
                        break;
                    }
                }
            }
        }
    }

    /**
     * 处理查看页面数据
     *
     * @param itemList
     * @param etvList
     * @param map
     * @param time
     * @param num
     */
    private void dataValue3(List<ElectronTemplateValue> itemList, List<ElectronTemplateValue> etvList, Map<String, Object> map, String time, int num) {
        if (itemList != null && itemList.size() > 0) {
            Iterator<ElectronTemplateValue> it = itemList.iterator();
            while (it.hasNext()) {
                ElectronTemplateValue e = it.next();
                String startTime = DateUtil.DateToString(e.getStartTime(), "HH");
                if (time.equals(startTime)) {
                    dataValue2(etvList, map, e.getEtvNumber(), num);
                    map.put("description", e.getDescription() != null ? e.getDescription() : "");
                    map.put("createTime", DateUtil.DateToString(e.getCreateTime(), DateStyle.YYYY_MM_DD_HH_MM_CN));
                    map.put("createName", e.getCreateName());
                    it.remove();
                    break;
                }
            }
        }
    }

    /**
     * 处理数据值
     *
     * @param etvList   值集合
     * @param map       存放map
     * @param etvNumber 值分组
     * @param num       标题长度
     */
    private void dataValue2(List<ElectronTemplateValue> etvList, Map<String, Object> map, Integer etvNumber, int num) {
        if (etvList != null && etvList.size() > 0) {
            Iterator<ElectronTemplateValue> it = etvList.iterator();
            int i = 0;
            while (it.hasNext()) {
                ElectronTemplateValue etv = it.next();
                if (etv.getEtvNumber().equals(etvNumber)) {
                    map.put(etv.getEtiId(), etv.getEtvValue());
                    it.remove();
                    i++;
                    if (i == num) {
                        break;
                    }
                }
            }
        }
    }

    /**
     * 处理OPC值和标题
     *
     * @param etiList
     * @param titleList
     */
    private void opcValue(List<ElectronTemplateItem> etiList, List<Map<String, Object>> titleList, boolean is) {
        List<String> itemName = new ArrayList<String>();
        Map<String, Object> titleMap = null;
        for (ElectronTemplateItem eti : etiList) {
            if (eti.getIsSynOpc() != null && eti.getIsSynOpc() == true && is) {
                itemName.add(eti.getOpc());
            }
            titleMap = new HashMap<String, Object>();
            titleMap.put("fieldId", eti.getEtiId());
            titleMap.put("orgName", eti.getOrgName());
            titleMap.put("unit", eti.getUnit() != null ? eti.getUnit().trim() : "");
            titleMap.put("fieldName", eti.getEpName());
            titleMap.put("min", eti.getMinRangeValue() != null ? eti.getMinRangeValue() : "");
            titleMap.put("max", eti.getMaxRangeValue() != null ? eti.getMaxRangeValue() : "");
            titleList.add(titleMap);
        }
        if (is) {
            String sb = "{\"itemName\":" + JSONArray.toJSON(itemName) + "}";
//                sb = "{\"itemName\":[\"Channel1.Device1.12345678901234567\",\"Channel1.Dvice1.12345678901234568\"]} ";
            String str = null;
            try {
                //处理连接超时
                str = HttpClientUtil.httpPostWithJson(configUril, sb);
            } catch (Exception e) {

            }
//                str = "{\"value\": [[\"1\", 129011111111111.0132132132132, \"Good\", \"05/03/17 10:27:45\"], [\"2\", \"1.13213213213213\", \"Good\", \"05/03/17 10:27:45\"],[\"3\", \"1.13213132132\", \"Good\", \"05/03/17 10:27:45\"]" +
//                        "[\"4\", \"12345.132132465\", \"Good\", \"05/03/17 10:27:45\"],[\"5\", \"365465.0054564646\", \"Good\", \"05/03/17 10:27:45\"]]}";
            if (StringUtils.isNotEmpty(str) && str.contains("value")) {
                EntityValue ev = JSONObject.parseObject(str, EntityValue.class);
                List<String> list = ev.getValue();
                if (list != null && list.size() > 0) {
                    if (itemName.size() == 1) {
                        for (ElectronTemplateItem eti : etiList) {
                            if (list.get(0).equals(eti.getOpc())) {
                                eti.setOpcValue(list.get(1));
                                break;
                            }
                        }
                    } else if (itemName.size() > 1) {
                        for (ElectronTemplateItem eti : etiList) {
                            isValue(list, eti);
                        }
                    }
                }
            }
        }
    }

    /**
     * 处理特性值对应OPC值
     *
     * @param list
     * @param eti
     * @return
     */
    private void isValue(List<String> list, ElectronTemplateItem eti) {
        for (String s : list) {
            List<String> strList = JSONArray.parseArray(s, String.class);
            if (strList.get(0).equals(eti.getOpc())) {
                eti.setOpcValue(strList.get(1));
                break;
            }
        }
    }

}
